var form = layui.form,
    laydate = layui.laydate,
    upload = layui.upload,
    table = layui.table,
    $ = layui.jquery,
    drawbackId = getQueryVariable("drawbackId");

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
//表单初始值
if (drawbackId != "") {
    form.val("editor-form", {
        "invoicenumber": "获取登记ID",
    })
}
//附件信息
let annexData=[];
layer.ready(function () {
   $.ajax({
       url:"drawback/findDrawbackDetail",
       type:"POST",
       dataType:"json",
       contentType: 'application/json',
       data:JSON.stringify(drawbackId),
       success:function(res) {
           if (res.status == 200) {
               $("#drawbackId").val(res.data.drawbackId);
               $("#drawbackCode").val(res.data.drawbackCode);
               $("#shippingDate").val(res.data.shippingDate);
               $("#customerName").val(res.data.customerName);
               $("#businessMode").val(res.data.businessMode);
               $("#declarationDate").val(res.data.declarationDate);
               $("#invoiceCode").val(res.data.invoiceCode);
               $("#currencyName").val(res.data.currencyName);
               $("#rmbRate").val(res.data.rmbRate);
               $("#usdRate").val(res.data.usdRate);
               $("#declarationAmount").val(res.data.declarationAmount);
               $("#theoreticalTaxRefund").val(res.data.theoreticalTaxRefund);
               $("#contractCode").val(res.data.contractCode);
               $("#exporterName").val(res.data.exporterName);
               $("#operatorName").val(res.data.operatorName);
               $("#actualTaxRefund").val(res.data.actualTaxRefund);
               $("#registerDate").val(res.data.registerDate);
               $("#remarks").val(res.data.remarks);
               annexData=res.data.costAnnexVOList;
               table.reload('attachmenttableid',{data : annexData});
           }

       }
   });
    $.ajax({
        url: "drawback/getThisUser",
        success: function (res) {
            $("#drawbackOperatorName").val(res.data.name);
            $("#drawbackOperatorCode").val(res.data.code);
        }
    });
});
//监听提交
form.on('submit(form-element)', function (datas) {
    let reqData={};
    //获取附件数据
    let annexReqs = table.cache["attachmenttableid"];
    reqData["annexList"] = annexReqs;
    reqData['drawbackId']=datas.field.drawbackId;
    reqData['actualTaxRefund']=datas.field.actualTaxRefund;
    reqData['drawbackOperatorName']=datas.field.drawbackOperatorName;
    reqData['drawbackOperatorCode']=datas.field.drawbackOperatorCode;
    reqData['registerDate']=datas.field.registerDate;
    reqData['remarks']=datas.field.remarks;
    reqData['drawbackStatus']=3;//登记箱

    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(reqData),
        url:"drawback/addDrawback",
        success:function(res) {
            if(res.status==200){
                layer.msg("保存成功", {icon: 6});
                setTimeout(function () {
                    //保存成功则刷新提交过来的界面 并关闭此页面
                    parent.detab("views/jsp/Money/taxrebates.jsp");
                    parent.intab("views/jsp/Money/taxrebates.jsp","退税")
                    parent.detab("views/jsp/Money/tpl/newtaxrebates.jsp"+(drawbackId==''?'':'?drawbackId='+drawbackId));
                },1000);
                return false;
            }
        }
    });


});
form.on('submit(form-element2)', function (data) {
    let reqData={};
    reqData['drawbackId']=data.field.drawbackId;
    reqData['actualTaxRefund']=data.field.actualTaxRefund;
    reqData['drawbackOperatorName']=data.field.drawbackOperatorName;
    reqData['drawbackOperatorCode']=data.field.drawbackOperatorCode;
    reqData['registerDate']=data.field.registerDate;
    reqData['remarks']=data.field.remarks;
    reqData['drawbackStatus']=4;//完成箱
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(reqData),
        url:"drawback/addDrawback",
        success:function(res) {
            if(res.status==200){
                layer.msg("保存完成", {icon: 6});
                setTimeout(function () {
                    //保存成功则刷新提交过来的界面 并关闭此页面
                    parent.detab("views/jsp/Money/taxrebates.jsp");
                    parent.intab("views/jsp/Money/taxrebates.jsp","退税")
                    parent.detab("views/jsp/Money/tpl/newtaxrebates.jsp"+(drawbackId==''?'':'?drawbackId='+drawbackId));
                },1000);
                return false;
            }
        }
    });

});

table.on('tool(moaidetailtable)', function (obj) {
    if (obj.event === 'del') {
        layer.confirm('真的删除行么', function (index) {
            //需要删除的ID：data.id
            obj.del();
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
        });
    }
});

table.on('toolbar(moaidetailtable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'imporcustomsdeclarationform':
            layer.open({
                type: 2,
                area: ['1488px', '800px'],
                content: 'views/jsp/Money/tpl/imporcustomsdeclarationform.jsp'
            });
            break;
        case 'new':
            var oldData = table.cache["moaidetailtableid"];
            var data1={"id":oldData.length+1,warehousename:"",number:"",taxrebatesforpeopleprice:"",amountsubtotal:"",costprice:"",costsubtotal:"",productcode:""};
            oldData.push(data1);
            table.reload('moaidetailtableid',{data : oldData});
            break;
        case 'del':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["moaidetailtableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("moaidetailtableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

//---附件
table.render({
    elem: '#attachment'
    , data: annexData
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
let uploadListIns = upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexData.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexData}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                let id = data.id;
                for (var i = 0; i < annexData.length; i++) {
                    if (annexData[i].id == id) {
                        annexData.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexData}); //ajax删除成功之后刷新表格
            });
    }
});
//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}
//---操作日志
let data2=[];
table.render({
    elem: '#otherwarehouselog'
    , data: data2
    , cols: [[
        {field: 'operationtype', title: '操作类型', fixed: true}
        , {field: 'theoperator', title: '操作员'}
        , {field: 'operationdate', title: '操作日期'}
        , {field: 'modifythecontent', title: '修改内容'}
    ]]
    , id: 'logtableid'
    , height: 380
    , limit: 30//显示的数量
    , page: true
});